<?php
/* SVN FILE: $Id: app_controller.php 7945 2008-12-19 02:16:01Z gwoo $ */
/**
 * Short description for file.
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
 * @package       cake
 * @subpackage    cake.cake.libs.controller
 * @since         CakePHP(tm) v 0.2.9
 * @version       $Revision: 7945 $
 * @modifiedby    $LastChangedBy: gwoo $
 * @lastmodified  $Date: 2008-12-18 18:16:01 -0800 (Thu, 18 Dec 2008) $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */
/**
 * This is a placeholder class.
 * Create the same file in app/app_controller.php
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       cake
 * @subpackage    cake.cake.libs.controller
 */
class AppController extends Controller {
	
	var $admin = array();
	var $allowedActions = null;
	//Fieldname image into table
	var $fieldSource = array('image', 'images', 'source');
	//Foldername contain image. Default is image (..app/webroot/img/image)
	var $folderContain = 'img';
	var $components = array('Auth');
	
	/**
    * beforeFilter
     * 
     * Application hook which runs prior to each controller action
     * 
     * @access public 
     */
    function beforeFilter(){
        //Override default fields used by Auth component
        $this->Auth->fields = array('username'=>'username','password'=>'password');
        //Set application wide actions which do not require authentication
//        $this->Auth->allow('*');//IMPORTANT for CakePHP 1.2 final release change this to $this->Auth->allow(array('display'));
        //Set the default redirect for users who logout
        $this->Auth->logoutRedirect = '/users/login';
        //Set the default redirect for users who login
        $this->Auth->loginRedirect = '/home/index';
        //Extend auth component to include authorisation via isAuthorized action
        $this->Auth->authorize = 'controller';
        //Restrict access to only users with an active account
        //$this->Auth->userScope = array('User.active = 1');
        //Pass auth component data over to view files
        $this->set('Auth',$this->Auth->user());
//        debug($this->Auth->user()); die();

      //nếu chưa set ngôn ngữ thì ngôn ngữ mặc định sẽ là vi
   		if (!isset($_SESSION['lang']))
    	{
    		$_SESSION['lang'] = 'vi';
    	}
    }
    
	function beforeRender(){
        //If we have an authorised user logged in then set up the admin element
        if($this->Auth->user()){
            $controllerList = Configure::listObjects('controller');
            foreach($controllerList as $controllerItem){
                if($controllerItem <> 'App'){
                    if($this->__permitted($controllerItem,'index')){
                        $this->admin[] = $controllerItem;
                    }
                }
            }
        }
        $this->set('admin',$this->admin);
    }
    function isAuthorized(){
        return $this->__permitted($this->name,$this->action);
    }
    function __permitted($thisController,$thisAction){
        //Ensure checks are all made lower case
        $thisController = low($thisController);
        $thisAction = low($thisAction);
        //Firstly users:logout is never restricted so set up a bypass
        if($thisController.':'.$thisAction == 'users:logout'){
            return true;
        }
        //Now if allowedActions has not yet benn created, create it
        if(!$this->allowedActions){
            //Import the User Model so we can build up the permission cache
            App::import('Model', 'User');
            $thisUser = new User;
            $thisGroup = new Group;
            //Now bring in the current users full record along with groups
            $thisGroups = $thisUser->find(array('User.id'=>$this->Auth->user('id')));
            $thisGroup = $thisGroups['Group'];
            $thisPermissions = $thisUser->Group->find(array('Group.id'=>$thisGroup['id']));
            $thisPermissions = $thisPermissions['Permission'];
            foreach($thisPermissions as $thisPermission){
            	$this->allowedActions[]=$thisPermission['name'];
            }
        }
        //Now check the cache to see if we have permission set
        foreach($this->allowedActions as $allowedAction){
            if($allowedAction == '*'){
                return true;//Super Admin Bypass Found
            }
            if($allowedAction == $thisController.':'.$thisAction){
                return true;//Specific permission found
            }
        }
        
        return false;
    }
	
	
	function dataSearch()
	{
		// the page we will redirect to
		$tmp = explode('/', $this->referer());
		if (isset($tmp[2]) && !empty($tmp[2]))
		{
			$url['action'] = $tmp[2];
		} else {
			$url['action'] = 'index';
		}
	
		// build a URL will all the search elements in it
		// the resulting URL will be
		// example.com/cake/posts/index/Search.keywords:mykeyword/Search.tag_id:3
		foreach ($this->data as $k=>$v){
			foreach ($v as $kk=>$vv){
				$url[$k.'.'.$kk]=$vv;
			}
		}
		
		// redirect the user to the url
		$this->redirect($url, null, true);
	}
	
	/**
	 * Function multiDelete
	 * @author hoanbn
	 * @tutorial delete multi record in table
	 * @param $this->data['record']
	 *
	 */
	function multiDelete()
	{
		$model = $this->modelClass;
		if (isset($this->data['record']))
		{
			foreach ($this->data['record'] as $key=>$val)
			{
				if ($val == 1)
				{
					//Get data record and delete image
					$this->$model->recursive = -1;
					$data = $this->$model->findById($key);
					foreach ($this->fieldSource as $image)
					{
						
						if (isset($data[$model][$image]))
						{
							//Delete image and thumbnail image
							@unlink(WWW_ROOT .  $this->folderContain . DS . $data[$model][$image]);
							@unlink(WWW_ROOT .  $this->folderContain . DS . 'thumbnail' . DS . $data[$model][$image]);
						}
					}
					if ($this->$model->del($key))
					{
						  $this->_flash(__(sprintf('Deleted record %d.',$key),true),'success');
					} else {
						  $this->_flash(__(sprintf('Deleted record %d.',$key),true),'error');
						
					}
				}
			}
		}
		$this->redirect($this->referer());
	}
	
	function _flash($message,$type='message') {
                $messages = (array)$this->Session->read('Message.multiFlash');
                $messages[] = array('message'=>$message, 'layout'=>'default', 'params'=>array('class'=>$type));
                $this->Session->write('Message.multiFlash', $messages);
    }
	
}
?>